﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Serie_Counter.DataLayer
{
    public class IO_FileMoving
    {
        private FileInfo[] files;

        public IO_FileMoving( string root)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(root);
            FileInfo[] filesMkv = directoryInfo.GetFiles("*.mkv", SearchOption.AllDirectories);
            FileInfo[] filesAvi = directoryInfo.GetFiles("*.avi", SearchOption.AllDirectories);

            files = new FileInfo[filesMkv.Length + filesAvi.Length];
            Array.Copy(filesMkv, files, filesMkv.Length);
            Array.Copy(filesAvi, files, filesAvi.Length);
        }

        /// <summary>
        /// move matched files (mkv and avi)
        /// </summary>
        /// <param name="searchKey">searched string</param>
        /// <param name="destenation">destenation path</param>
        /// <param name="root">root folder to search in</param>
        /// <returns>int[2], [0] = failed entries, [1] = succesfull entries</returns>
        public int[] moveFiles(string searchKey, string destenation)
        {
            
            int[] returnResult = new int[2];
            string[] tempParts = searchKey.Split(' ');

            //Split the title of the serie on spaces, and se if the file contains every part
            //ex. The mentalist would be => "The" and "mentalist"
            //if those 2 parts are containing in the file name, it will be an episode of that serie
            //notice that this is case sensitiv therefor ToLower();
            foreach (FileInfo file in files)
            {
                bool move = false;
                for (int i = 0; i < tempParts.Length; i++)
                {
                    if (file.FullName.ToLower().Contains(tempParts[i].ToLower()))
                    {
                        move = true;
                    }
                    else
                    {
                        move = false;
                        break;
                    }
                }

                if (move)
                {
                    try
                    {
                        File.Move(file.FullName, destenation+"\\"+file.Name);
                        returnResult[1]++;
                    }
                    catch (Exception)
                    {
                        //inc failed files
                        returnResult[0]++;
                    }
                }
            }

            return returnResult;
        }
    }
}
